<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            background-color: #bbb;
        }

        #canvas {
            background-color: #000;
        }
    </style>
</head>

<body>
    <canvas id="canvas" width="400" height="400"></canvas>
</body>
<script src="./utils.js"></script>
<script src="./arrow.js"></script>
<script src="./ball.js"></script>
<script src="./ship.js"></script>
<script>
    window.onload = () => {
        var canvas = document.getElementById("canvas");
        var context = canvas.getContext("2d");
        var mouse = utils.captureMouse(canvas),
            ship = new Ship(),
            vr = 0,
            vx = 0,
            vy = 0,
            thrust = 0;

        ship.x = canvas.width / 2;
        ship.y = canvas.height / 2;

        window.addEventListener("keydown", function (e) {
            switch (e.keyCode) {
                case 37:
                    vr = -3;
                    break;
                case 39:
                    vr = 3;
                    break;
                case 38:
                    thrust = 0.05;
                    ship.showFlame = true;
                    break;
            }
        }, false);

        window.addEventListener("keyup", function () {
            vr = 0;
            thrust = 0;
            ship.showFlame = false;
        }, false);

        (function drawFrame() {
            window.requestAnimationFrame(drawFrame, canvas);
            context.clearRect(0, 0, canvas.width, canvas.height);

            ship.rotation += vr * Math.PI / 180;
            var angle = ship.rotation,
                ax = Math.cos(angle) * thrust,
                ay = Math.sin(angle) * thrust,
                left = 0,
                right = canvas.width,
                top = 0,
                bottom = canvas.height;

            vx += ax;
            vy += ay;
            ship.x += vx;
            ship.y += vy;

            // 超出屏幕的话
            if (ship.x - ship.width / 2 > right) {
                ship.x = left - ship.width / 2
            } else if (ship.x + ship.width / 2 < left) {
                ship.x = right + ship.width / 2
            }
            if (ship.y - ship.height / 2 > bottom) {
                ship.y = top - ship.height / 2
            } else if (ship.y + ship.height / 2 < top) {
                ship.y = bottom + ship.height / 2
            }

            ship.draw(context);
        }())
    };
</script>

</html>